package com.sfc.service.impl;

import com.sfc.dto.UserDTO;
import com.sfc.entity.UserEntity;
import com.sfc.repo.UserRepository;
import com.sfc.service.UserService;
import com.sfc.utils.AuthzUtils;
import com.sfc.utils.BeanUtils;
import com.sfc.utils.Md5Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Created by heylear.cai on 2016/3/11.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;


    @Override
    public UserDTO getUserByUsernameAndPasswd(String username, String passwd) {
        UserEntity ue = userRepository.findUserByUsername(username);
        if (ue != null
                && ue.getPasswd().equals(Md5Encrypt.md5(passwd))){
            AuthzUtils.setCurrentUserId(ue.getId());
            return BeanUtils.copy(ue, UserDTO.class);
        }
        throw new RuntimeException("用户名或密码错误");
    }

    @Override
    public Long saveUser(UserDTO user) {
        UserEntity ue = userRepository.findUserByUsername(user.getUsername());
        Assert.isNull(ue, "用户名已注册");
        ue = BeanUtils.copy(user, UserEntity.class);
        userRepository.save(ue);
        AuthzUtils.setCurrentUserId(ue.getId());
        return ue.getId();
    }
}
